package org.andao.commons.taglib.security;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;

import org.andao.commons.taglib.BaseTagSupport;
import org.andao.core.utils.ExStringUtils;
import org.andao.security.SpringSecurityHelper;
import org.andao.security.cache.CacheSecManager;
import org.andao.security.model.Resource;
import org.andao.security.model.User;
import org.apache.commons.lang.StringUtils;



/**
 * 根据用户登录名，获取用户的系统菜单<p>
 * 
 * @author Marco.hu(hzg139@163.com)
 */
public class CurrentUserSystemMenuTag extends BaseTagSupport{

	private static final long serialVersionUID = -4457310703441926570L;
	

	@Override
	public int doStartTag() throws JspException {
		User user = SpringSecurityHelper.getCurrentUser();
		if(ExStringUtils.isEmpty(user.getUsername())){
			throw new JspException("无法输出用户菜单，原因：非法的用户名.");
		}
		try{
			// 用户有权限的id
			//String rightIds = (String)MemeryCacheManager.getCache(CacheSecManager.CACHE_SEC_USER_RES_IDS).get(SpringSecurityHelper.getCurrentUserName());
			// 用户顶级菜单id
			//String topMenuId = (String)MemeryCacheManager.getCache(CacheSecManager.CACHE_SEC_USER_TOP_MENU_IDS).get(SpringSecurityHelper.getCurrentUserName());
			
			//Map<String, Object> userMap = UserDetailsServiceImpl.getUserMap();
			//if(null != userMap){
				String rightIds = user.getUserRightsIds();
				String topMenuId = user.getUserTopMenuIds();
				// 从缓存获取
				List<Resource> list = new ArrayList<Resource>();
				for(String mid : topMenuId.split(",")) {
					if(!StringUtils.isEmpty(mid)) {
						//list.add((Resource)MemeryCacheManager.getCache(CacheSecManager.CACHE_SEC_RESOURCE).get(mid));
						list.add(CacheSecManager.getResourceFromCache(mid));
					}
				}
				
				// 构造树形html
				this.pageContext.getOut().append(printTree(list,rightIds));
			//}
			
		}catch(Exception e){
			logger.error("输出用户菜单出错:{}",e.fillInStackTrace());
		}
		return EVAL_PAGE;
	}
	
	/**
	 * 菜单树
	 * @param list
	 * @return
	 */
	private String printTree(List<Resource> list,String userRightsIds){
		StringBuffer sb = new StringBuffer();
		for (Resource resource : list) {
			
			// 没有权限  跳过
			if(userRightsIds.indexOf(resource.getResourceid())<0) continue;
			
			
			if(resource.getResourceLevel() == 1){
				sb.append("<div class=\"accordionHeader\"><h2><span>Folder</span>"+resource.getResourceName()+"</h2></div>");
				sb.append("<div class=\"accordionContent\"><ul class=\"tree treeFolder\">");
			}
			if(resource.getResourceType().equals("menu")) { 
				sb.append("<li><a ");
				if(!resource.getResourcePath().equals("#")){
					sb.append("href='"+getBaseUrl()+ resource.getResourcePath()+"' title='"+resource.getResourceName()+"' target=\"navTab\" rel='"+resource.getResourceCode()+"'");
				}
				sb.append(">"+resource.getResourceName()+"</a>");
				
				List<Resource> children = CacheSecManager.getChildren(resource.getResourceid());
				
				// 递归 子集合
				if(!children.isEmpty() && children.size()>0){					
					if(children.get(0).getResourceType().equals("menu")) {
						sb.append("<ul>");					
					}
					sb.append(printTree(children,userRightsIds));
					if(children.get(0).getResourceType().equals("menu")) {
						sb.append("</ul>");
					}
				}								
				sb.append("</li>");
			}
			if(resource.getResourceLevel() == 1){
				sb.append("</ul></div>");
			}
		}
		return sb.toString();
	}
}
